package cn.yunhe.control;

import cn.yunhe.util.DateUtil;
import cn.yunhe.entity.Reply;
import cn.yunhe.entity.Topic;
import cn.yunhe.entity.User;
import cn.yunhe.server.ReplyServer;
import cn.yunhe.server.UserServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/ReplyTopicServlet")
public class ReplyTopicServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pId = request.getParameter("pId"); //获取主贴编号
        String title = request.getParameter("title"); //获取主贴标题
        String context = request.getParameter("context"); //获取回帖内容
        String pTime = DateUtil.date2StringDateTime(new Date()); //获取回帖时间
        Topic topic =new Topic();  //新建topic对象
        topic.setpId(Integer.parseInt(pId)); //补充topic属性
        topic.setTitle(title);

        HttpSession session = request.getSession(); //获取session对象
        //从session中获取用户名和密码
        String username = (String) session.getAttribute("username");
        //获取server类对象
        UserServer userServer = new UserServer();
        ReplyServer replyServer = new ReplyServer();
        //执行sql语句,获取user对象
        List<User> list = userServer.getUser(username);
        if (list != null && list.size() > 0) {
            User user =list.get(0); //获取user对象
            Reply reply = new Reply(title,context,pTime,user,topic); //补充回帖属性
            boolean flag = replyServer.replyTopic(reply); //执行回帖方法,回帖内容插入数据库
            if (flag){
                request.setAttribute("result","回复成功!!");
                request.getRequestDispatcher("replyTopic.jsp").forward(request,response);
            }else {
                request.setAttribute("result","回复失败!!");
                request.getRequestDispatcher("replyTopic.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("result","回复失败!!");
            request.getRequestDispatcher("replyTopic.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
